<!-- 我的页面（个人中心） -->
<template>
  <div class="my_page">
    <div class="blue_area" id="user_bg">
      <div class="pop">
        <van-popover v-model:show="showPopover" placement="bottom-end">
          <van-uploader
            :max-count="1"
            :max-size="5 * 1024 * 1024"
            @oversize="onOversize"
            :before-read="beforeRead"
            :after-read="afterRead"
          >
            <van-button icon="exchange">更改头像</van-button>
          </van-uploader>
          <van-uploader
            :max-count="1"
            :max-size="5 * 1024 * 1024"
            @oversize="onOversize"
            :before-read="beforeRead"
            :after-read="uploadBg"
          >
            <van-button icon="exchange">更改背景</van-button>
          </van-uploader>
          <template #reference>
            <van-icon name="ellipsis" size="25" />
          </template>
        </van-popover>
      </div>
      <div class="avatar_div">
        <van-image
          id="avatar_image"
          round
          width="7em"
          height="7em"
          :src="avatarUrl"
          @click="enlargeAvatar"
        />
      </div>
      <div class="avatar_bottom_div" v-if="isLogin">
        您还未登陆，请先
        <span class="login_span_style" @click="toLoginPage">登陆</span>
        ！
      </div>
      <div class="avatar_under_div_login" v-if="!isLogin">
        <div>
          <span class="user_name">
            {{ userName }}({{ nickName }})
            <van-icon
              id="edit_icon"
              @click="clickEditIcon"
              name="https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/icon/edit.png"
            ></van-icon>
          </span>
        </div>
        <div class="diary_blog_div">
          <span>&emsp;{{ dayCount }}天</span>
        </div>
        <div class="tag_list">
          <span v-for="index in tagViews" :key="index" class="tag_span">
            {{ index }}
          </span>
        </div>
      </div>
    </div>

    <!-- 关注，被关注，日记，博客-->
    <div class="concern_main">
      <div class="concern_center" @click="toUserConcernPage(1)">
        <div class="concern_size">{{ userConcern }}</div>
        <div class="concern_font_color">关注</div>
      </div>
      <div class="concern_center" @click="toUserConcernPage(2)">
        <div class="concern_size">{{ userConcerned }}</div>
        <div class="concern_font_color">被关注</div>
      </div>
      <div class="concern_center" @click="toDiaryListPage">
        <div class="concern_size">{{ diaryCount }}</div>
        <div class="concern_font_color">日记</div>
      </div>
      <div class="concern_center" @click="toBlogListPage">
        <div class="concern_size">{{ blogCount }}</div>
        <div class="concern_font_color">博客</div>
      </div>
    </div>

    <!-- 我的收藏，我的资料，消息中心，关于 -->
    <div class="collect_info_message_about">
      <div class="collent" @click="toMyCollectionPage">
        <div class="icon_collect_font">
          <span>
            &emsp;
            <van-icon name="star" />
            &nbsp;
          </span>
          <span>我的收藏</span>
        </div>
        <div><van-icon name="arrow" /></div>
      </div>
      <div class="collent" @click="toMyInfomationPage">
        <div class="icon_collect_font">
          <span>
            &emsp;
            <van-icon name="label" />
            &nbsp;
          </span>
          <span>我的资料</span>
        </div>
        <div><van-icon name="arrow" /></div>
      </div>
      <div class="collent" @click="toMessageCenterPage">
        <div class="icon_collect_font">
          <span>
            &emsp;
            <van-icon name="comment" />
            &nbsp;
          </span>
          <span>消息中心</span>
        </div>
        <div><van-icon name="arrow" /></div>
      </div>
      <div class="collent" @click="toSettingPage">
        <div class="icon_collect_font">
          <span>
            &emsp;
            <van-icon name="setting" />
            &nbsp;
          </span>
          <span>设置</span>
        </div>
        <div><van-icon name="arrow" /></div>
      </div>
      <div class="collent" @click="toAboutPage">
        <div class="icon_collect_font">
          <span>
            &emsp;
            <van-icon name="info" />
            &nbsp;
          </span>
          <span>关于</span>
        </div>
        <div><van-icon name="arrow" /></div>
      </div>
      <div class="collent" @click="exit">
        <div class="icon_collect_font">
          <span>
            &emsp;
            <van-icon
              name="https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/icon/tuichu-x.png"
            />
            &nbsp;
          </span>
          <span>退出登陆</span>
        </div>
        <div><van-icon name="arrow" /></div>
      </div>
    </div>

    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
    <br />
  
    <!-- 点击编辑图标显示的弹出层 -->
    <van-popup
      v-model:show="editNameShow"
      position="bottom"
      round
      :style="{ height: '20%', padding: '10px' }"
    >
      <van-field
        v-model="userName"
        clearable
        label="用户名"
        left-icon="user-o"
        placeholder="输入用户名"
        :error-message="userNameErrorMessage"
      />
      <van-field
        v-model="nickName"
        clearable
        label="昵称"
        left-icon="https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/icon/nickname.png"
        placeholder="输入昵称"
        :error-message="nickNameErrorMessage"
      />
      <div>
        <van-button type="primary" block @click="editNameFunc">确定</van-button>
      </div>
    </van-popup>

    <!-- 点击头像显示的遮罩层 -->
    <van-overlay :show="avatarEnlargeShow" @click="avatarEnlargeShow = false">
      <div class="wrapper">
        <div id="block"></div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import { client } from '../utils/alioss'
import requests from '../api/request'
import {
  getLoginUserInfoByToken,
  updateUserAvatar,
  updateUserBg,
  isSimpleUserName,
  updateCurrentUserNameAndNickName,
} from '../api/personal.js'
export default {
  data() {
    return {
      isLogin: false,
      userName: 'fantasy', // 用户名
      nickName: '范占国', // 昵称
      dayCount: 5, // 注册天数
      userTag: ['二次元', '王者荣耀', '抖音常驻'], // 用户标签
      tagViews: [], // 显示在个人中心的用户标签，由userTag截取前三个
      diaryCount: 9, // 用户自己的日记总数
      blogCount: 8, // 用户自己的博客总数
      showPopover: false, // 控制气泡弹出框的显示
      avatarUrl: '',
      userBackImage: '', // 用户的背景墙图片的URL
      avatarEnlargeShow: false, // 控制点击头像遮罩层的显示
      userAid: null, // 当前登录用户的aid
      userConcern: 0, // 当前登陆用户关注的用户数量
      userConcerned: 0, // 当前登陆用户有多少用户关注
      editNameShow: false, // 控制编辑弹出框的显示
      userNameErrorMessage: '', // 用户名的错误提示
      nickNameErrorMessage: '', // 昵称的错误提示
    }
  },

  created() {
    // 判断是否登陆了
    this.checkIsLogin()

    // 设置背景图
    this.setUserBg()
  },

  methods: {
    // 去登陆页面
    toLoginPage() {
      this.$router.push('/login')
    },

    // 设置背景图
    setUserBg() {
      setTimeout(() => {
        // 给用户背景墙初始化背景
        let userBg = document.getElementById('user_bg')
        userBg.style.backgroundImage = `url("${this.userBackImage}")` //设置背景图的的地址
        userBg.style.backgroundRepeat = 'no-repeat' //设置背景不平铺
        userBg.style.backgroundSize = 'cover' //设置背景图像的尺寸
      }, 100)
    },

    // 判断是否登陆了
    checkIsLogin() {
      if (
        localStorage.getItem('token') == null ||
        localStorage.getItem('token') === ''
      ) {
        this.isLogin = true
      } else {
        this.isLogin = false
        requests({
          url: '/user/checkToken',
          method: 'get',
          headers: {
            token: localStorage.getItem('token'),
          },
        }).then((res) => {
          if (res.data.state === false && res.data.msg === 'token已过期！') {
            this.isLogin = true
          } else {
            // 没过期，请求后端接口，获取用户有关信息
            getLoginUserInfoByToken().then((res) => {
              // console.log(res)
              this.userName = res.data.data.userName
              this.nickName =
                res.data.data.nickName === null || res.data.data.nickName === ''
                  ? '昵称暂无'
                  : res.data.data.nickName
              this.dayCount = res.data.data.dayCount
              this.diaryCount = res.data.data.diaryCount
              this.blogCount = res.data.data.blogCount
              this.userTag = res.data.data.userTag
              this.tagViews = this.userTag.slice(0, 3)
              this.avatarUrl = res.data.data.avatar
              // console.log(res.data.data.backImage)

              this.userBackImage = res.data.data.backImage
              this.setUserBg()
              this.userAid = res.data.data.currentUserAid
              this.userConcern = res.data.data.userConcern
              this.userConcerned = res.data.data.userConcerned
            })
            this.isLogin = false
          }
        })
      }
    },

    // 点击编辑图标修改自己的用户名
    clickEditIcon() {
      this.editNameShow = true
    },

    // 点击确定修改用户名和用户昵称
    editNameFunc() {
      if (this.userName === '') {
        this.userNameErrorMessage = '用户名不能为空'
      } else {
        // console.log(this.userName);
        // 查询是否有相同的用户名（保证用户名的唯一性）
        isSimpleUserName(this.userName)
          .then((res) => {
            if (res.data.data) {
              this.userNameErrorMessage = '该用户名已存在，请重新输入'
            } else {
              // 更新当前登陆用户的用户名和昵称
              const params = {
                userName: this.userName,
                nickName: this.nickName,
              }
              updateCurrentUserNameAndNickName(params).then((res) => {
                if (res.data.code === 10000) {
                  this.$toast({
                    type: 'success',
                    message: res.data.message,
                    duration: 800,
                  })
                  // this.checkIsLogin();
                  this.editNameShow = false
                } else {
                  this.$toast({
                    type: 'fail',
                    message: res.data.message,
                    duration: 800,
                  })
                  this.editNameShow = false
                }
              })
            }
          })
          .catch(() => {
            this.$toast({
              type: 'fail',
              message: '异常，请稍后再试！',
              duration: 800,
            })
            this.editNameShow = false
          })
      }
    },

    // 上传图片大小的限制
    onOversize() {
      this.$toast({
        duration: 500,
        message: '文件大小不能超过5M！',
        type: 'fail',
      })
    },

    // 上传图片之前的格式判断
    beforeRead(file) {
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        return true
      } else {
        this.$toast('请上传 jpg 或 png 格式的图片')
        return false
      }
    },

    // 图片上传至服务器
    afterRead(file) {
      // 定义唯一文件名
      var fileName =
        'user/avatar_userbg/' + `${Date.parse(new Date())}` + '.jpg'
      client()
        .multipartUpload(fileName, file.file)
        .then(() => {
          // this.$toast.success('上传成功！')
          this.avatarUrl =
            'https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/' + fileName

          // 后端更新当前用户的头像
          this.updateCurrentUserAvatar()
        })
    },

    uploadBg(file) {
      // 定义唯一文件名
      var fileName =
        'user/avatar_userbg/' + `${Date.parse(new Date())}` + '.jpg'
      client()
        .multipartUpload(fileName, file.file)
        .then(() => {
          // this.$toast.success('上传成功！')
          this.userBackImage =
            'https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/' + fileName

          // 后端更新当前用户的背景图
          this.updateCurrentUserBg()
        })
    },

    // 更新当前用户的背景图
    updateCurrentUserBg() {
      updateUserBg(this.userBackImage).then((res) => {
        if (res.data.code === 10000) {
          this.$toast.success(res.data.message)
          this.setUserBg()
          this.showPopover = false
        } else {
          this.$toast.fail(res.data.message)
        }
      })
    },

    // 更新当前用户的头像
    updateCurrentUserAvatar() {
      updateUserAvatar(this.avatarUrl).then((res) => {
        if (res.data.code === 10000) {
          this.$toast.success(res.data.message)
          // this.checkIsLogin()
          this.showPopover = false
        } else {
          this.$toast.fail(res.data.message)
        }
      })
    },

    // 点击头像放大
    enlargeAvatar() {
      this.avatarEnlargeShow = true
      setTimeout(() => {
        let block = document.getElementById('block')
        // console.log(block)
        block.style.backgroundImage = `url("${this.avatarUrl}")`
        block.style.backgroundRepeat = 'no-repeat'
        block.style.backgroundSize = 'cover'
      }, 100)
    },

    // 去用户关注的页面
    toUserConcernPage(param) {
      this.$router.push({
        path: '/userConcern',
        query: {
          state: param, // 用户关注的人状态为1，该用户被哪些人关注，状态为2
          userAid: this.userAid,
        },
      })
    },

    // 去该用户的日记列表页面
    toDiaryListPage() {
      this.$router.push({
        path: '/otherUserDiaryList',
        query: {
          userAid: this.userAid,
        },
      })
    },

    // 去博客列表页面
    toBlogListPage() {
      this.$router.push({
        path: '/otherUserBlogList',
        query: {
          userAid: this.userAid,
        },
      })
    },

    // 去我的收藏页面
    toMyCollectionPage() {
      this.$router.push('/myCollectionPage')
    },

    // 去我的资料页面
    toMyInfomationPage() {
      this.$router.push('/myInfomation')
    },

    // 去消息中心页面
    toMessageCenterPage() {
      this.$router.push('/messageCenter')
    },

    // 去设置页面
    toSettingPage() {
      this.$router.push('/setting')
    },

    // 去关于页面
    toAboutPage() {
      this.$router.push('/about')
    },

    // 退出登陆
    exit() {
      this.$dialog
        .confirm({
          title: '',
          message: '确定退出吗？',
        })
        .then(() => {
          // 移除token
          localStorage.removeItem('token')
          // 跳转到登陆页面
          this.$router.push('/login')
        })
        .catch(() => {
          // on cancel
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.blue_area {
  width: 100%;
  height: 16em;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  padding-top: 20px;
}
.avatar_div {
  width: 7em;
  height: 7em;
  background-color: aliceblue;
  margin: auto;
  border-radius: 50%;
  position: relative;
  top: 2.5em;
}
.avatar_bottom_div {
  color: rgba(113, 109, 109, 0.829);
  font-size: 16px;
  text-align: center;
  width: 15em;
  /* background-color: aliceblue; */
  margin: auto;
  position: relative;
  top: 4.5em;
}
.avatar_under_div_login {
  color: rgba(113, 109, 109, 0.829);
  font-size: 16px;
  text-align: center;
  width: 15em;
  /* background-color: aliceblue; */
  margin: auto;
  position: relative;
  top: 3em;
}
.login_span_style {
  color: rgba(176, 227, 227, 0.763);
  font-size: 18px;
}
.tag_list {
  width: 100%;
  height: 1.5em;
  /* background-color: aliceblue; */
  overflow-y: hidden;
  margin-top: 5px;
}
.diary_blog_div {
  margin-top: 5px;
  color: wheat;
}
.tag_span {
  width: fit-content;
  margin-left: 3px;
  margin-right: 3px;
  margin-bottom: 10em;
  border: 1px solid;
  padding: 2px;
  background-color: rgb(125, 201, 216);
  border-radius: 5px;
  color: rgb(210, 215, 219);
}
.user_name {
  color: rgba(45, 103, 153, 0.895);
  font-size: larger;
  font-weight: 600;
}
.pop {
  text-align: right;
  width: 95%;
  height: 1px;
}
#avatar_image {
  box-shadow: -20px 0 20px 5px rgba(213, 255, 145, 0.5),
    0px -20px 20px 5px rgba(145, 255, 191, 0.5),
    20px 0 20px 5px rgba(82, 255, 220, 0.5),
    0 20px 20px 5px rgba(239, 255, 91, 0.5);
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

#block {
  width: 100%;
  height: 300px;
  background-size: cover;
  background-repeat: no-repeat;
}
.concern_main {
  display: flex;
  justify-content: space-around;
  margin-top: 15px;
}
.concern_center {
  text-align: center;
}
.concern_size {
  font-size: 23px;
  font-weight: 600;
}
.concern_font_color {
  color: #909399;
  font-size: small;
}
.collent {
  display: flex;
  justify-content: space-between;
  height: 60px;
  margin-top: 1px;
  border-bottom: 1px solid white;
  align-items: center;
  font-size: 18px;
  color: #606266;
  letter-spacing: 2px;
}
.collect_info_message_about {
  padding-left: 10px;
  padding-right: 10px;
  margin-top: 20px;
  background-color: #8ac9e4be;
  border-radius: 5px;
}
.my_page {
  overflow-y: scroll;
}
#edit_icon {
  position: relative;
  top: 4px;
}
</style>
